// <!--
//  * 严肃声明：
//  * 开源版本请务必保留此注释头信息，若删除我方将保留所有法律责任追究！
//  * 可正常分享和学习源码，不得用于违法犯罪活动，违者必究！
//  * Copyright (c) 2022 APThink David唐 all rights reserved.
//  * 版权所有，侵权必究！
//  *
// -->
import { i18n } from "@/i18n"
import { read, utils } from "xlsx"
import { storage } from "./Storage"
import { json2object } from "./ObjectUtil"

export function localDisableTip(): boolean {
  return storage.get("ApthinkDisableTip")=="true";
}

export function saveLocalDisableTip(data: boolean) {
  storage.set("ApthinkDisableTip", data?"true":"false");
}

export function localLanguage(): string {
  return storage.get("ApthinkLanguage") || "zh";
}

export function saveLocalLanguage(data: string) {
  storage.set("ApthinkLanguage", data);
}

export function localTheme(): string {
  return storage.get("ApthinkTheme") || "light";
}

export function saveLocalTheme(data: string) {
  storage.set("ApthinkTheme", data);
}

export function saveToken(data: string) {
  storage.set("ApthinkToken", data);
}

export function getToken() {
  return storage.get("ApthinkToken");
}

export function removeToken() {
  storage.del("ApthinkToken");
  storage.del("ApthinkMenu");
  storage.del("ApthinkPermission");
  setCookie("ApthinkToken", "", -1);
}

export function hasMenuRight(to: any) {
  // David 首页不用设置菜单权限
  if (to.path == "/") return true
  const menus = json2object(storage.get("ApthinkMenu"))
  const url = menus.find((y: any) => {
    return y == to.path
  });
  return !!url
}

export function hasPermission(item: string) {
  return true
  // David 用户菜单功能权限
  const permissions = json2object(storage.get("ApthinkPermission"))
  const p = permissions.find((y: string) => {
    return y == item;
  });
  return p != undefined || localStorage.useruid == "administrator"
}

/**
 * cookie中存取相关信息
 */
export function setCookie(name: string, value: string, expiredays?: number) {
  const Days = expiredays==null?3:expiredays;
  const exp = new Date();
  exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 30);
  document.cookie =
    name + "=" + encodeURIComponent(value) + ";expires=" + exp.toString();
}

export function getCookie(name: string) {
  const reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
  const arr = document.cookie.match(reg);

  if (arr) {
    return decodeURIComponent(arr[2]);
  } else {
    return null;
  }
}

export function compareArray(a1: Array<object>, a2: Array<object>) {
  if (a1 === a2) return true;
  if ((!a1 && a2) || (a1 && !a2)) return false;
  if (a1.length !== a2.length) return false;
  for (let i = 0, n = a1.length; i < n; i++) {
    if (a1[i] !== a2[i]) return false;
  }
  return true;
}

export function getScreenType() {
  const size = window.screen.width;
  let result = "md";
  if (size < 576) result = "sm";
  else if (size >= 1200) result = "xl";
  // console.log(window.screen.width, window.screen.height, result);
  return result;
}

interface FieldItem {
  label: string;
  key: string;
  sortable: boolean;
}

export function setFieldLanguage(fields: Array<Array<FieldItem>>) {
  fields.forEach((x) => {
    x.forEach((y) => {
      y.label = i18n.global.t("label." + y.key);
    });
  });
}

export function debounce(
  fn: Function,
  delay: number,
  immdiate = false,
  resultCallback: any
) {
  let timer: any = null;
  let isInvoke = false;

  function _debounce(...arg: any[]) {
    if (timer) clearTimeout(timer);
    if (immdiate && !isInvoke) {
      const result = fn.apply(fn.caller, arg);
      if (resultCallback && typeof resultCallback === "function")
        resultCallback(result);
      isInvoke = true;
    } else {
      timer = setTimeout(() => {
        const result = fn.apply(fn.caller, arg);
        if (resultCallback && typeof resultCallback === "function")
          resultCallback(result);
        isInvoke = false;
        timer = null;
      }, delay);
    }
  }

  _debounce.cancel = function () {
    if (timer) clearTimeout(timer);
    timer = null;
    isInvoke = false;
  };

  return _debounce;
}

// 入参 fmt-格式: 'YYYY-mm-dd HH:MM:SS' date-日期
export function dateFormat(fmt: any, date: Date) {
  let ret;
  const opt: any = {
    "Y+": date.getFullYear().toString(), // 年
    "m+": (date.getMonth() + 1).toString(), // 月
    "d+": date.getDate().toString(), // 日
    "H+": date.getHours().toString(), // 时
    "M+": date.getMinutes().toString(), // 分
    "S+": date.getSeconds().toString(), // 秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  };
  for (const k in opt) {
    ret = new RegExp("(" + k + ")").exec(fmt);
    if (ret) {
      fmt = fmt.replace(
        ret[1],
        ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0")
      );
    }
  }
  return fmt;
}

// 读取Excel文档，返回Json对象
export function readXLSX(file: File) {
  const nameSplit = file.name.split(".");
  const format = nameSplit[nameSplit.length - 1];
  if (!["xlsx", "csv"].includes(format)) {
    return false;
  }
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsBinaryString(file);
    reader.onload = function (evt) {
      const data = evt.target?.result; // 读到的数据
      try {
        const workbook = read(data, { type: "binary" });
        const wsname = workbook.SheetNames[0]; //这里取第一张表,您可以自行调整,亦可以采取便利再操作
        const ws = utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
        resolve(ws);
      } catch (err) {
        reject("some wrong with import");
      }
    };
  });
}

export function getJsonColumn(data: any[]) {
  const columnFields = new Set();
  data.forEach((d) => {
    for (const attr in d) {
      columnFields.add(attr);
    }
  });
  return Array.from(columnFields);
}

